import * as THREE from 'three';
// 导入轨道控制器
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
// 导入动画库
import gsap from 'gsap';
// 导入dat.gui
import * as dat from 'dat.gui';
// 导入connon引擎
import * as CANNON from 'cannon-es';

// 目标：使用cannon引擎
console.log(CANNON);

// const gui = new dat.GUI();
// 1、创建场景
const scene = new THREE.Scene();

// 2、创建相机
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 300);

// 设置相机位置
camera.position.set(0, 0, 18);
scene.add(camera);
//添加环境光和平行光
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
const dirLight = new THREE.DirectionalLight(0xffffff, 0.5);
dirLight.castShadow = true;
scene.add(dirLight);

const renderer = new THREE.WebGLRenderer({ alpha: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
document.body.appendChild(renderer.domElement);
renderer.render(scene, camera);
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
const axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);
const clock = new THREE.Clock();

const textureLoader = new THREE.TextureLoader();
const texture = textureLoader.load('../assets/image/maoge/Tiles111_1K_Color.jpg');
const textureAo = textureLoader.load('../assets/image/maoge/Tiles111_1K_AmbientOcclusion.jpg');

const floor = new THREE.Mesh(new THREE.PlaneBufferGeometry(100, 100), new THREE.MeshStandardMaterial({ map: texture }));
floor.position.set(0, -10, 0);
floor.rotation.x = -Math.PI / 2;
floor.receiveShadow = true;
scene.add(floor);

const cubeArr = [];

// 创建物理世界
// const world = new CANNON.World({ gravity: 9.8 });
const world = new CANNON.World();
world.gravity.set(0, -9.8, 0);
// 创建击打声音
const hitSound = new Audio('./assets/music/lanqiu1.mp3');
//设置物体材质
const sphereWorldMaterial = new CANNON.Material('cube');

// 创建球和平面
function createCube() {
  const sphereGeometry = new THREE.BoxGeometry(1, 1, 1);
  const sphereMaterial = new THREE.MeshStandardMaterial({
    //   color: '#FF9800',
    map: texture,
    alphaMap: textureAo,
    aoMap: textureAo
  });
  const sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
  sphere.castShadow = true;
  scene.add(sphere);
  // 创建物理小球形状
  const sphereShape = new CANNON.Box(new CANNON.Vec3(0.5, 0.5, 0.5));
  // 创建物理世界的物体
  const sphereBody = new CANNON.Body({
    shape: sphereShape,
    position: new CANNON.Vec3(0, 0, 0),
    //   小球质量
    mass: 1,
    //   物体材质
    material: sphereWorldMaterial
  });
  // 给物体添加力 第一参数是添加的力的大小和方向，第二参数是施加的力所在的身体的位置
  sphereBody.applyLocalForce(new CANNON.Vec3(180, 0, 0), new CANNON.Vec3(0, 0, 0));
  // 将物体添加至物理世界
  world.addBody(sphereBody);

  // 添加监听事件碰撞
  sphereBody.addEventListener('collide', hiteEvent);
  cubeArr.push({
    mesh: sphere,
    body: sphereBody
  });
}
// createCube();
const floorWorldMaterial = new CANNON.Material('floor');

// 物理世界创建地面
const floorShape = new CANNON.Plane();
const floorBody = new CANNON.Body();

// 当质量为0的时候，可以使得物体保持不动
floorBody.mass = 0;
floorBody.addShape(floorShape);
floorBody.material = floorWorldMaterial;
// 地面位置
floorBody.position.set(0, -10, 0);
// 旋转地面的位置 向量
floorBody.quaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), -Math.PI / 2);
world.addBody(floorBody);

// 设置两种材质的碰撞参数
const defaultContactMaterial = new CANNON.ContactMaterial(sphereWorldMaterial, floorWorldMaterial, {
  // 摩擦力
  friction: 0.1,
  // 弹性
  restitution: 0.7
});
// 将材料的关联设置添加到物理世界
world.addContactMaterial(defaultContactMaterial);
// 设置世界碰撞的默认材料，如果材料没有设置都使用默认材料
world.defaultContactMaterial = defaultContactMaterial;

// 碰击事件
function hiteEvent(e) {
  // 获取碰撞的强度
  const impactStrength = e.contact.getImpactVelocityAlongNormal();
  console.log(impactStrength);
  if (impactStrength > 2) {
    // 音频重新从零播放;
    hitSound.currentTime = 0;
    hitSound.volume = impactStrength / 100;
    hitSound.play();
  }
}
function render() {
  //   let time = clock.getElapsedTime();
  let deltaTime = clock.getDelta();
  // 更新物理引擎里世界的物体
  world.step(1 / 120, deltaTime);
  cubeArr.forEach(item => {
    item.mesh.position.copy(item.body.position);
    // 设置渲染的物理跟随世界的物理物体旋转
    // quaternion四元素/
    item.mesh.quaternion.copy(item.body.quaternion);
  });
  // sphere.position.copy(sphereBody.position);
  renderer.render(scene, camera);
  //   渲染下一帧的时候就会调用render函数
  requestAnimationFrame(render);
}

render();

// 监听画面变化，更新渲染画面
window.addEventListener('click', () => {
  createCube();
});

// 监听画面变化，更新渲染画面
window.addEventListener('resize', () => {
  //   console.log("画面变化了");

  // 更新摄像头
  camera.aspect = window.innerWidth / window.innerHeight;
  //   更新摄像机的投影矩阵
  camera.updateProjectionMatrix();

  //   更新渲染器
  renderer.setSize(window.innerWidth, window.innerHeight);
  //   设置渲染器的像素比
  renderer.setPixelRatio(window.devicePixelRatio);
});
